package com.gogowan.agroenterprise.widget;

import it.sauronsoftware.ftp4j.FTPClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gogowan.agroenterprise.OperationActivity;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.FtpUpload;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.contorl.OperationFtpUpload;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.UploadPicturesInfo;
import com.gogowan.agroenterprise.model.UploadPicturesResultInfo;
import com.gogowan.agroenterprise.model.VideoInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 视频专题的插入图片
 * 
 */
public class OperationVideoGridView extends ControlView {

	private Context context;
	private BaseActivity operation;
	// private Bitmap bitmap;
	private String uploadfile;
	private ProgressDialog progressDialog;
	private GridView gridView;
	// private List<PicturesInfo> list = new ArrayList<PicturesInfo>();
	private OperationVideosAdapter adapter;
	private SharedPreferences sharedPreferences;

	private Object ress;

	public OperationVideoGridView(Context context, String data) {
		super(context, data);
		this.context = context;
		initControl();
		initData();
	}

	public OperationVideoGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		this.setOrientation(LinearLayout.VERTICAL);
		// this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
		// LayoutParams.FILL_PARENT));
		initControl();
		initData();
	}

	@Override
	public void setData(String newData) {
		super.setData(newData);
	}

	public List<VideoInfo> getList() {
		return adapter.getDataList();
	}

	public void setList(List<VideoInfo> list) {
		adapter.setList(list);
		// this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
		// LayoutParams.WRAP_CONTENT));
	}

	@Override
	public String getData() {
		return null;// IconUtils.imgToStr(bitmap);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				VideoInfo videoInfo = (VideoInfo) msg.obj;

				adapter.addVideoInfo(videoInfo);
				gridView.setVisibility(View.VISIBLE);
				break;
			default:
				break;
			}
		}

	};

	public void clear() {
		adapter.clear();
	}

	public void initData() {

		sharedPreferences = context.getSharedPreferences("LoginINfo", 0);
		String string = sharedPreferences.getString("saveLoginInfo", "");
		LoginResultInfo loginResultInfo = (LoginResultInfo) Utils.fromJSON(
				string, LoginResultInfo.class);
		uploadfile = loginResultInfo.getFtpfile();

		/*
		 * sharedPreferences = context.getSharedPreferences("LoginINfo",0);
		 * String dataStr = sharedPreferences .getString("saveLoginInfo", null);
		 * if (!Utils.isEmpty(dataStr)) { LoginResultInfo loginResultInfo =
		 * (LoginResultInfo)Utils.fromJSON(dataStr, LoginResultInfo.class);
		 * String path = loginResultInfo.getFtpulr(); if (Utils.checkHttp(path))
		 * { } }
		 */
	}

	/**
	 * 初始化控件
	 * 
	 */
	@SuppressWarnings("deprecation")
	public void initControl() {

		final LayoutInflater inflater = LayoutInflater.from(context);
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.pictures_grid_view, null);
		this.addView(layout);

		gridView = (GridView) layout.findViewById(R.id.pictures_gride_gv);
		gridView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		adapter = new OperationVideosAdapter(context, null, gridView);
		gridView.setAdapter(adapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				if ((adapter.getCount() - 1) == position) {
				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(
							context);
					builder.setTitle("选择方式");
					builder.setItems(new String[] { "删除" },
							new AlertDialog.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									if (which == 0) {
										/*
										 * try { List<VideoInfo> list =
										 * adapter.getList(); VideoInfo
										 * videoInfo = list.get(position); //
										 * context.startActivity(Utils //
										 * .goUrl(path // + videoInfo //
										 * .getVideourl())); Intent intent = new
										 * Intent(Intent.ACTION_VIEW);
										 * intent.setDataAndType(Uri.parse(path+
										 * videoInfo.getVideourl()),"video/*");
										 * context.startActivity(intent); }
										 * catch (ActivityNotFoundException e) {
										 * Toast.makeText(context,
										 * "找不到播放器！",Toast.LENGTH_SHORT).show();
										 * } catch (Exception e) {
										 * Toast.makeText(context,
										 * "无法播放视频！",Toast.LENGTH_SHORT).show();
										 * } } else if (which == 1) {
										 */
										boolean isDel = adapter.del(position);
										if (adapter.getCount() <= 1) {
											gridView.setVisibility(View.GONE);
											operation.closeVedioView();
										} else {
											gridView.setVisibility(View.VISIBLE);
										}
										if (isDel) {
											Toast.makeText(context, "删除视频成功！",
													Toast.LENGTH_SHORT).show();
										} else {
											Toast.makeText(context, "删除视频失败！",
													Toast.LENGTH_SHORT).show();
										}
									}
								}
							});
					builder.show();
				}
			}
		});
	}

	public void onViewResult(int requestCode, int resultCode,
			final Intent data, final FTPClient ftp) {
		try {
			if (resultCode == Activity.RESULT_OK) {
				if (requestCode == 2 || requestCode == 3) {// 视频
					Uri originalUri = data.getData(); // 获得图片的uri
					// 无论是本地的视频还是系统拍摄的视频地址都是媒体库中的地址
					final String path = Utils.getImageAbsolutePath(context,
							originalUri);
					// String[] proj = { MediaStore.Images.Media.DATA,
					// MediaStore.Images.Media.SIZE };
					// /*
					// * // 好像是android多媒体数据库的封装接口，具体的看Android文档 Cursor cursor =
					// * ((Activity) context).managedQuery( originalUri, proj,
					// * null, null, null);
					// */
					//
					// // android.database.StaleDataException: Attempted to
					// access
					// // a cursor after it has been closed.
					// // 4.0以上平台报这个错
					// ContentResolver resolver = ((Activity) context)
					// .getContentResolver();
					// Cursor cursor = resolver.query(originalUri, proj, null,
					// null, null);
					// // 按我个人理解
					// // 这个是获得用户选择的图片的索引值
					// int column_index = cursor
					// .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					// // 将光标移至开头
					// // ，这个很重要，不小心很容易引起越界
					// cursor.moveToFirst();
					// // 最后根据索引值获取图片路径
					// final String path = cursor.getString(column_index);
					// cursor.close();
					if (Utils.isEmpty(path)) {

						return;
					}

					// // 显示视频描述框
					// LayoutInflater inflater = LayoutInflater.from(context);
					// View view = inflater.inflate(R.layout.image_dialog,
					// null);
					// final EditText text = (EditText) view
					// .findViewById(R.id.image_dialog_et_message);

					// new AlertDialog.Builder(context)
					// .setView(view)
					// .setPositiveButton("保存",
					// new AlertDialog.OnClickListener() {
					// @Override
					// public void onClick(
					// DialogInterface dialog,
					// int which) {
					// String description = text.getText()
					// .toString();
					try {
						OperationFtpUpload ftpUpload = new OperationFtpUpload(
								context, uploadfile, 1, ftp, null);

						UploadVideoAsync uploadAsync = new UploadVideoAsync(
								ftpUpload, "");
						uploadAsync.execute(path);
					} catch (Exception e) {
						// MobclickAgent.reportError(context,
						// e);
						Toast.makeText(context, "上传视频失败", Toast.LENGTH_SHORT)
								.show();
					}
				}

			}
		} catch (Exception e) {
			// MobclickAgent.reportError(context, e);
			Toast.makeText(context, "获取文件失败", Toast.LENGTH_SHORT).show();
		}
	}

	@SuppressLint({ "NewApi", "NewApi" })
	public class UploadVideoAsync extends MyAsyncTask {
		private OperationFtpUpload ftpUpload;
		private String image;
		private String video;
		private String description;

		public UploadVideoAsync(OperationFtpUpload ftpUpload, String description) {
			this.ftpUpload = ftpUpload;
			this.description = description;
		}

		@Override
		protected Object doInBackground(Object... params) {
			String path = (String) params[0];
			FileOutputStream b = null;
			try {

				File sdDir;
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					// Toast.makeText(context, "无SD卡",
					// Toast.LENGTH_SHORT).show();
					return null;
				} else {
					sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
				}

				// SimpleDateFormat dateFormat = new SimpleDateFormat(
				// "yyyyMMddHHmmssSSS");
				// String dateStr = dateFormat.format(new Date());
				String dateStr = System.currentTimeMillis() + "";
				// 得到源文件的后缀
				String houzhui = path.substring(path.lastIndexOf(".") + 1)
						.trim();
				video = dateStr + "." + houzhui;
				String fileName = sdDir.getPath() + "/AgricultureSystem/Video/"
						+ video;

				// 复制到指定文件夹并重命名
				Utils.copyfile(new File(path), new File(fileName), true);

				// ftpUpload = new FtpUpload(
				// MainActivity.this, FtpUpload.VIDOE_FILE);
				// ftpUpload.ftpUpload(fileName);

				// 三种不同的获取视频缩略图方法
				// Bitmap bitmap = Utils.getVideoThumbnail(context, fileName);
				// Bitmap bitmap=Utils.getVideoThumbnail(path);
				// Bitmap bitmap = Utils.createVideoThumbnail(path);

				Bitmap bitmap = null;
				// 获取视频的缩略图
				bitmap = ThumbnailUtils.createVideoThumbnail(fileName,
						MediaStore.Images.Thumbnails.MICRO_KIND);
				System.out.println("w" + bitmap.getWidth());
				System.out.println("h" + bitmap.getHeight());
				bitmap = ThumbnailUtils.extractThumbnail(bitmap, 60, 60,
						ThumbnailUtils.OPTIONS_RECYCLE_INPUT);

				image = dateStr + ".jpg";
				String sfileName = sdDir.getPath()
						+ "/AgricultureSystem/Video/" + image;
				if (!new File(sfileName).getParentFile().exists()) {
					new File(sfileName).getParentFile().mkdirs();
				}

				b = new FileOutputStream(sfileName);
				// bitmap = ThumbnailUtils.extractThumbnail(
				// bitmap, 100, 100);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

				// 图片回收
				if (bitmap != null && !bitmap.isRecycled()) {
					bitmap.recycle();
					bitmap = null;
				}

				// 截图存储到图片目录
				/*
				 * ftpUpload.changeDirectory(FtpUpload.IMAGE_FILE);
				 * ftpUpload.ftpUpload(sfileName);
				 */
				// 小图
				File f = new File(sfileName);
				long length = f.length();
				bitmap = Utils.decodeFile(new File(sfileName), 70);

				// ftpUpload.ftpUpload(sfileName);

				ftpUpload.ftpUpload(fileName, sfileName);
				if (new File(fileName).exists()) {
					new File(fileName).delete();
				}
				/*
				 * if(new File(sfileName).exists()){ new
				 * File(sfileName).delete(); }
				 */
				// this.bitmap=bitmap;

				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					// MobclickAgent.reportError(context, e);
					Toast.makeText(context, "outputStream close error",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (Exception e) {
					// MobclickAgent.reportError(context, e);
					Toast.makeText(context, "outputStream close error",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				} catch (Throwable e) {
					// MobclickAgent.reportError(context, e);
					Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
				return "1";

			} catch (Exception e) {
				Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
				// MobclickAgent.reportError(context, e);
			} catch (OutOfMemoryError e) {
				Toast.makeText(context, "需创建缓存文件，内存空间不足！", Toast.LENGTH_SHORT)
						.show();
				e.printStackTrace();
				// MobclickAgent.reportError(context, e);
			} finally {
				// try {
				// b.flush();
				// b.close();
				// } catch (IOException e) {
				// Toast.makeText(context, "outputStream close error",
				// Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
				// } catch (Exception e) {
				// Toast.makeText(context, "outputStream close error",
				// Toast.LENGTH_SHORT).show();
				// e.printStackTrace();
				// }
			}
			return null;
		}// 返回json串作为onPostExecute(Object res)的参数 }

		@Override
		protected void onPostExecute(Object res) {
			ress = res;

			Runnable runnable = new Runnable() {

				@Override
				public void run() {
					try {
						if (!ftpUpload.close()) {
							return;
						}

						if (ress != null) // 上传成功
						{
							VideoInfo videoInfo = new VideoInfo();
							videoInfo.setImageurl(image);
							videoInfo.setVideourl(video);
							videoInfo.setDescription(description);

							android.os.Message msg = new android.os.Message();
							msg.what = 0;
							msg.obj = videoInfo;
							handler.sendMessage(msg);

							// adapter.addVideoInfo(videoInfo);
						} else {
							Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
									.show();
						}
					} catch (Exception e) {
						Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
						// MobclickAgent.reportError(context, e);
					} catch (Throwable e) {
						Toast.makeText(context, "上传失败", Toast.LENGTH_SHORT)
								.show();
						e.printStackTrace();
						// MobclickAgent.reportError(context, e);
					} finally {
						ftpUpload.close();
					}
				}
			};

			new Thread(runnable).start();

			super.onPostExecute(res);
		}
	}

	/**
	 * 上传异步
	 * 
	 * @author zk
	 * 
	 */
	public class UploadAsync extends MyAsyncTask {
		private String description;

		public UploadAsync(String description) {
			this.description = description;
		}

		@Override
		protected Object doInBackground(Object... params) {
			UploadPicturesInfo uploadPicturesInfo = (UploadPicturesInfo) params[0]; // 取得要提交的对象
			String json = Utils.toJSON(uploadPicturesInfo); // 将对象转化为 json串
			int type = 1;// Utils.getTempValue(Temp.UPLOAD); // 设置相应的请求类型
			Message message = new Message(type, false, json); // 将json转化为Message对象
			String result = Utils.postCommit(
					context.getString(R.string.first_url)
							+ context.getString(R.string.first_url_page),
					message); // 获取服务器提交路径，提交信息，并接收返回的json串
			return result; // 返回json串作为onPostExecute(Object res)的参数
		}

		@Override
		protected void onPostExecute(Object res) {
			progressDialog.dismiss(); // 关闭ProgressDialog
			String results = (String) res; // 接收回传的json串
			Message message = stringToMessage(results); // 将json串转换成Message消息盒子

			if (message == null) { // 如果Message对象为null,连接服务器失败
				Toast.makeText(context, "连接服务器失败！", Toast.LENGTH_SHORT).show();
				return; // 结束该程序
			}
			String content = Utils.getMessageContent(message); // 获得消息内容
			UploadPicturesResultInfo uploadPicturesResultInfo = (UploadPicturesResultInfo) Utils
					.fromJSON(content, UploadPicturesResultInfo.class); // 内容转换成返回的对象模型
			int result = uploadPicturesResultInfo.getResult(); // 获得返回结果类型
			String resultinfo = uploadPicturesResultInfo.getResultinfo(); // 获得返回结果内容

			if (result == 1110) // 上传成功
			{
				VideoInfo videoInfo = new VideoInfo();
				videoInfo.setImageurl(uploadPicturesResultInfo.getUrlimg());
				videoInfo.setVideourl(uploadPicturesResultInfo.getUrlvideo());
				videoInfo.setDescription(description);

				adapter.addVideoInfo(videoInfo);
				// list最后一条空的赋值
				// List<PicturesInfo> list = adapter.getList();
				// list.set(list.size() - 1, picturesInfo);
				// adapter.setList(list);

			} else if (result == -1110) { // 上传失败并显示失败原因
				Toast.makeText(context, resultinfo, Toast.LENGTH_SHORT).show();
			} else { // 未知错误
				Toast.makeText(context, "未知错误", Toast.LENGTH_SHORT).show();
			}
			super.onPostExecute(result);
		}
	}

	public Message stringToMessage(String results) {
		Message message = null;
		if (results.equals("") || results == null) {
			return message;
		}
		message = Utils.jsonToMessage(results);// 转换成消息盒子
		return message;
	}

	public void setEnabled(boolean isEnabled) {
		gridView.setEnabled(isEnabled);
	}

	public void setOperation(BaseActivity activity) {
		operation = activity;
	}

	public boolean isTypeOk(Intent data) {
		boolean isOk = false;
		Uri originalUri = data.getData(); // 获得图片的uri
		String path = Utils.getImageAbsolutePath(context, originalUri);
		String houzhui = path.substring(path.lastIndexOf(".") + 1).trim();
		String type = context.getString(R.string.video_upload_type);
		if (!Utils.isEmpty(path) && !Utils.isEmpty(houzhui)) {
			if (type.contains(houzhui)) {
				isOk = true;
			}
		}
		return isOk;
	}
}